package biznussoft.fieldservice360.fragments;

import java.util.HashMap;

import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import biznussoft.fieldservice360.HomeActivity;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.lookup.ItemIdLookUp;
import biznussoft.fieldservice360.model.Bean_Class;
import biznussoft.fieldservice360.model.MaterialModel;
import biznussoft.fieldservice360.utils.Session;

import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class MaterialFragment extends BaseFragment implements OnClickListener{
	private TextView tvAction,tvTechnician,tvItemid,tvSerialId,tvQuantity,tvDiscription,tvFailureCode,tvFailureCodeDescription,tvActivity,tvEdittechnician;
	private EditText etQuantity,etDiscount,etFailureCode,etFailureCodeDescription;
	private RestClient client;
	private CheckBox billable,exChange,cbEditBillable,cbEditExchange;
	private LinearLayout editMode,viewMode;
	private Spinner spAction;
	private MaterialModel model;
	public static EditText etitemId;
	private Button save;
	String id;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.material_detail_fragment, null);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

		MenuItem addContact = menu.add("Edit");
		MenuItemCompat.setShowAsAction(addContact, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addContact.setIcon(R.drawable.edit); 
		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 
		super.onCreateOptionsMenu(menu, inflater);
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		/* if(item.getTitle().equals("Material")){
			 	viewMode.setVisibility(View.GONE);
				editMode.setVisibility(View.VISIBLE);
		 }*/
		if(item.getTitle().equals("Edit")){

			viewMode.setVisibility(View.GONE);
			editMode.setVisibility(View.VISIBLE);
			if(billable.isChecked()){
				cbEditBillable.setChecked(true);
			}else{
				cbEditBillable.setChecked(false);
			}
			if(exChange.isChecked()){
				cbEditExchange.setChecked(true);
			}else{
				cbEditExchange.setChecked(false);
			}
			tvEdittechnician.setText(model.getTechnician());
			etitemId.setText(model.getItemId());
			etQuantity.setText(model.getQuantity());
			etFailureCode.setText(model.getFailureCode());
			etFailureCodeDescription.setText(model.getFailureCodeDiscription());
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		client =  HomeActivity.mActivity.client;


		save = (Button) getView().findViewById(R.id.save);
		save.setOnClickListener(this);
		viewMode = (LinearLayout) getView().findViewById(R.id.lllayout_material_viewmode);
		editMode = (LinearLayout) getView().findViewById(R.id.lllayout_material_Editmode);

		etitemId = (EditText) getView().findViewById(R.id.etItemId);
		etitemId.setOnClickListener(this);

		etQuantity = (EditText) getView().findViewById(R.id.etQuantity);
		spAction = (Spinner) getView().findViewById(R.id.spAction);
		etDiscount = (EditText) getView().findViewById(R.id.etDiscount);
		etFailureCode = (EditText) getView().findViewById(R.id.etFailureCode);
		etFailureCodeDescription = (EditText) getView().findViewById(R.id.etfailurecodediscription);
		tvActivity = (TextView) getView().findViewById(R.id.tvActivity);
		tvEdittechnician = (TextView) getView().findViewById(R.id.tvEdittechnician);
		tvAction = (TextView) getView().findViewById(R.id.tvAction);
		tvTechnician = (TextView) getView().findViewById(R.id.tvtechnician);
		tvItemid = (TextView) getView().findViewById(R.id.tvItemId);
		tvSerialId = (TextView) getView().findViewById(R.id.tvserialId);
		tvQuantity = (TextView) getView().findViewById(R.id.tvQuantity);
		tvDiscription = (TextView) getView().findViewById(R.id.tvDescription);
		tvFailureCode = (TextView) getView().findViewById(R.id.tvFailureCode);
		tvFailureCodeDescription = (TextView) getView().findViewById(R.id.tvfailurecodediscription);

		billable = (CheckBox) getView().findViewById(R.id.cbBillable);
		exChange = (CheckBox) getView().findViewById(R.id.cbExchange);
		cbEditBillable = (CheckBox) getView().findViewById(R.id.cbeditBillable);
		cbEditExchange = (CheckBox) getView().findViewById(R.id.cbeditExchange);
	}




	public void showRecords(int position) {
		model = MaterialMasterFragment.materialList.get(position);
		tvTechnician.setText(model.getTechnician());
		tvAction.setText(model.getAction());
		tvActivity.setText(model.getActivityName());
		tvItemid.setText(model.getItemId());                                     
		tvSerialId.setText(model.getSerialId());
		tvQuantity.setText(model.getQuantity());
		//		tvDiscription.setText(model.getDiscription());
		tvFailureCode.setText(model.getFailureCode());
		tvFailureCodeDescription.setText(model.getFailureCodeDiscription());
		id = model.getId();

		if(model.isBillable()){
			billable.setChecked(true);
		}else{
			billable.setChecked(false);
		}
		if(model.isExChange()){
			exChange.setChecked(true);
		}else{
			exChange.setChecked(false);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.save:
			updateAccount(id);   
			break;
		case R.id.etItemId:
			ItemIdLookUp lookup = new ItemIdLookUp();
			lookup.getItemLookUp(getActivity(),"Material");
			break;
		default:
			break;
		}
	}

	public void updateAccount(String id){

		boolean billable =  cbEditBillable.isChecked();
		boolean exchange =  cbEditExchange.isChecked();

		String objectType = "FConnect__Material__c";
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("FConnect__Inventory_ID__c",Session.sItemId);                 
		fields.put("FConnect__Quantity__c",etQuantity.getText().toString());
		fields.put("FConnect__Billable__c", billable);
		fields.put("FConnect__Exchange__c",exchange);
		fields.put("FConnect__Failure_Code__c",etFailureCode.getText().toString());
		fields.put("FConnect__Failure_Code_Discription__c", etFailureCodeDescription.getText().toString());
		fields.put("FConnect__Action__c",spAction.getSelectedItem().toString());
		fields.put("FConnect__Quantity__c",etQuantity.getText().toString());
		try {
			RestRequest restRequest = RestRequest.getRequestForUpdate(Bean_Class.api_Version,objectType,id,fields);


			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {    
						finishFragment();
					}                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}

				//@Override
				public void onError(Exception exception) {

					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());

		}

	}
	public void finishFragment(){
		getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
	}
}
